package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 用户表业务处理
 **/
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 新增
     */
    public void add(User user) {
        String password = user.getPassword();
        //对用户的密码进行加密
        user.setPassword(passwordEncoder.encode(password));
        User dbuser = userMapper.selectByUserName(user.getUsername());
        if (ObjectUtil.isNotNull(dbuser)) {
            throw new CustomException("用户已存在");
        }
        userMapper.insert(user);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(User user) {
        User dbuser = userMapper.selectByUserName(user.getUsername());
        if (ObjectUtil.isNotNull(dbuser) && !Objects.equals(dbuser.getId(), user.getId())) {
            throw new CustomException("用户已存在");
        }
        user.setUpdatedAt(String.valueOf(LocalDateTime.now()));
        userMapper.updateById(user);
    }

    /**
     * 根据ID查询
     */
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    /**
     * 分页查询
     */
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        User dbuser = userMapper.selectByUserName(account.getUsername());
        if (ObjectUtil.isNull(dbuser)) {
            throw new CustomException("用户不存在");
        }
        if (!passwordEncoder.matches(account.getPassword(),dbuser.getPassword())) {
            throw new CustomException("原密码错误");
        }
        dbuser.setPassword(passwordEncoder.encode(account.getNewPassword()));
        userMapper.updateById(dbuser);
    }


}